import 'package:flutter/material.dart';

class NavItemBTM {
  IconData iconData;
  String text;
  NavItemBTM({this.iconData, this.text});
}

class AnchorBar extends StatefulWidget {
  AnchorBar({
    this.items,
    this.centerItemText,
    this.height: 60.0,
    this.iconSize: 24.0,
    this.backgroundColor,
    this.color,
    this.selectedColor,
    this.notchedShape,
    this.onTabSelected,
  }) {
    assert(this.items.length == 2 || this.items.length == 4);
  }
  final List<NavItemBTM> items;
  final String centerItemText;
  final double height;
  final double iconSize;
  final Color backgroundColor;
  final Color color;
  final Color selectedColor;
  final NotchedShape notchedShape;
  final ValueChanged<int> onTabSelected;

  @override
  createState() => AnchorBarState();
}

class AnchorBarState extends State<AnchorBar> {
  int _selectedIndex = 0;
  _updateIndex(index) {
    widget.onTabSelected(index);
    setState(() => _selectedIndex = index);
  }

  @override
  build(context) {
    List<Widget> items = List.generate(
        widget.items.length,
        (index) => _buildTabItem(
              item: widget.items[index],
              index: index,
              onPressed: _updateIndex,
            ));
    items.insert(items.length >> 1, _buildMiddleTabItem());
    return BottomAppBar(
      shape: widget.notchedShape,
      child: Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: items,
      ),
      color: widget.backgroundColor,
    );
  }

  _buildMiddleTabItem() => Expanded(
        child: SizedBox(
          height: widget.height,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              SizedBox(height: widget.iconSize),
              Text(
                widget.centerItemText ?? '',
                style: TextStyle(color: widget.color),
              ),
            ],
          ),
        ),
      );

  _buildTabItem({NavItemBTM item, int index, ValueChanged<int> onPressed}) {
    Color color = _selectedIndex == index ? widget.selectedColor : widget.color;
    return Expanded(
      child: SizedBox(
        height: widget.height,
        child: Material(
          type: MaterialType.transparency,
          child: InkWell(
            onTap: () => onPressed(index),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Icon(item.iconData, color: color, size: widget.iconSize),
                Text(item.text, style: TextStyle(color: color))
              ],
            ),
          ),
        ),
      ),
    );
  }
}
